<template>
  <div class="recognition-container">
    <!-- 扫描区域 -->
    <el-card class="scan-section">
      <h2>扫描</h2>
      <video ref="video" width="100%" height="300px"></video>
      <canvas style="display: none" id="canvasCamera" width="100%" height="300px"></canvas>
      <div v-if="imgSrc" class="img_bg_camera">
        <img :src="imgSrc" class="tx_img" />
      </div>
      <el-upload
        action="/api/upload"
        :headers="uploadHeaders"
        :on-success="handleSuccess"
        :show-file-list="false"
      >
        <el-button type="primary">上传作物图片</el-button>
      </el-upload>
      <div class="result-info" v-if="result">
        <h3>识别结果：{{ result.diseaseName }}</h3>
        <p>处理建议：{{ result.treatment }}</p>
      </div>
      <button @click="OpenCamera">打开摄像头</button>
      <button @click="CloseCamera">关闭摄像头</button>
      <button @click="setImage">拍照</button>
      <button @click="recordOrStop">视频录制</button>
    </el-card>

    <div class="features-section">
      <!-- 专家建议 -->
      <el-card class="feature-card" @click="navigateToExpertAnalysis">
        <h3>专家建议</h3>
        <el-button type="primary" @click="navigateToExpertAnalysis">查看专家分析</el-button>
      </el-card>

      <!-- 病虫害知识科普 -->
      <el-card class="feature-card" @click="navigateToKnowledgeBase">
        <h3>病虫害知识科普</h3>
        <el-button type="primary" @click="navigateToKnowledgeBase">了解详情</el-button>
      </el-card>
    </div>
    <a id="downLoadLink" style="display: none;"></a>
  </div>
</template>

<script>
export default {
  data() {
    return {
      result: null,
      uploadHeaders: {
        Authorization: `Bearer ${this.$store.state.token}`,
      },
      mediaStreamTrack: {},
      video_stream: '', // 视频stream
      imgSrc: '', // 拍照图片
      canvas: null,
      context: null,
      recordedBlobs: [], // 视频音频 blobs
      isRecord: false, // 视频是否正在录制
    };
  },
  mounted() {
    // 进入页面 自动调用摄像头
    this.getCamera();
  },
  methods: {
    // 调用打开摄像头功能
    getCamera() {
      // 获取 canvas 画布
      this.canvas = document.getElementById('canvasCamera');
      this.context = this.canvas.getContext('2d');
      // 旧版本浏览器可能根本不支持mediaDevices，我们首先设置一个空对象
      if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {};
      }
      navigator.mediaDevices
        .getUserMedia({
          video: true,
        })
          .then((stream) => {
          // 摄像头开启成功
          this.mediaStreamTrack = typeof stream.stop === 'function' ? stream : stream.getTracks()[0];
          this.video_stream = stream;
          this.$refs.video.srcObject = stream;
          this.$refs.video.play();
        })
        .catch(err => {
          console.log(err);
        });
    },
    // 拍照 绘制图片
    setImage() {
      console.log('拍照');
      // 点击canvas画图
      this.context.drawImage(
        this.$refs.video,
        0,
        0,
        200,
        100,
      );
      // 获取图片base64链接
      const image = this.canvas.toDataURL('image/png');
      this.imgSrc = image;
      this.$emit('refreshDataList', this.imgSrc);
    },
    // 打开摄像头
    OpenCamera() {
      console.log('打开摄像头');
      this.getCamera();
    },
    // 关闭摄像头
    CloseCamera() {
      console.log('关闭摄像头');
      if (this.video_stream) {
        this.video_stream.getTracks()[0].stop();
      }
    },
    // 录制或暂停
    recordOrStop() {
      if (this.isRecord) {
        this.stop();
      } else {
        this.record();
      }
    },
    // 视频录制
    record() {
      console.log('record');
      this.isRecord = !this.isRecord;
      let mediaRecorder;
      let options;
      this.recordedBlobs = [];
      if (typeof MediaRecorder.isTypeSupported === 'function') {
        // 根据浏览器来设置编码参数
        if (MediaRecorder.isTypeSupported('video/webm;codecs=vp9')) {
          options = {
            mimeType: 'video/webm;codecs=vp9',
          };
        } else if (MediaRecorder.isTypeSupported('video/webm;codecs=h264')) {
          options = {
            mimeType: 'video/webm;codecs=h264',
          };
        } else if (MediaRecorder.isTypeSupported('video/webm;codecs=vp8')) {
          options = {
            mimeType: 'video/webm;codecs=vp8',
          };
        }
        mediaRecorder = new MediaRecorder(this.video_stream, options);
      } else {
        console.log('当前不支持isTypeSupported，使用浏览器的默认编解码器');
        mediaRecorder = new MediaRecorder(this.video_stream);
      }
      mediaRecorder.start();
      // 视频录制监听事件
      mediaRecorder.ondataavailable = e => {
        console.log(e);
        // 录制的视频数据有效
        if (e.data && e.data.size > 0) {
          this.recordedBlobs.push(e.data);
        }
      };
      // 停止录像后增加下载视频功能，将视频流转为webm格式
      mediaRecorder.onstop = () => {
        const blob = new Blob(this.recordedBlobs, { type: 'video/webm' });
        this.recordedBlobs = [];
        // 将视频链接转换完可以用于在浏览器上预览的本地视频
        const videoUrl = window.URL.createObjectURL(blob);
        // 设置下载链接
        document.getElementById('downLoadLink').href = videoUrl;
        // 设置下载mp4格式视频
        document.getElementById('downLoadLink').download = 'media.webm';
        document.getElementById('downLoadLink').innerHTML = '下载视频文件';
        // 生成随机数字
        const rand = Math.floor((Math.random() * 1000000));
        // 生成视频名
        const name = `video${rand}.webm`;
        // setAttribute() 方法添加指定的属性，并为其赋指定的值
        document.getElementById('downLoadLink').setAttribute('download', name);
        document.getElementById('downLoadLink').setAttribute('name', name);
        // 0.5s后自动下载视频
        setTimeout(() => {
          document.getElementById('downLoadLink').click();
        }, 500);
      };
    },
    // 停止录制
    stop() {
      this.isRecord = !this.isRecord;
      if (!this.$refs.video.srcObject) return;
      const stream = this.$refs.video.srcObject;
      const tracks = stream.getTracks();
      // 关闭摄像头和音频
      tracks.forEach(track => {
        track.stop();
      });
    },
    handleSuccess(response) {
      this.result = response.data;
    },
    navigateToExpertAnalysis() {
      this.$router.push("/analysis");
    },
    navigateToKnowledgeBase() {
      this.$router.push("/knowledge");
    },
  },
};
</script>

<style scoped>
.recognition-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

.scan-section {
  width: 60%;
  text-align: center;
  padding: 20px;
}

.features-section {
  display: flex;
  justify-content: space-between;
  width: 60%;
  gap: 20px;
}

.feature-card {
  flex: 1;
  text-align: center;
  padding: 20px;
  cursor: pointer;
}

button {
  width: 100px;
  height: 40px;
  position: relative;
  bottom: 0;
  left: 0;
  background-color: rgb(22, 204, 195);
}
</style>
